<template>
  <div class="jurisdictionTemp">
    <el-form
      :model="formData"
      :disabled="dialogType === 'view'"
      :rules="rules"
      ref="form"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="用户集合" prop="partyIds">
            <el-input
              placeholder="请选择……"
              readonly
              type="textarea"
              :rows="10"
              resize="none"
              v-model="formData.partyIds"
            ></el-input>

            <div
              class="content"
              :class="dialogType === 'view' ? 'view' : ''"
              v-if="formData.partyIds && formData.partyIds.length !== 0"
            >
              <!--              <template v-for="{key,label} in users.keys">
                              <div v-if="users.selection[key].length>0">{{ label }}</div>
                              <template v-for="(item,index) in users.selection[key]">
                                <el-tag :key="item.pid" closable size="small" @close="closeTag(selectionPartyIds,index,'partyIds')">
                                  {{ item.name ? item.name : item.firstName }}
                                </el-tag>
                              </template>
                            </template>-->
              <template v-for="(item, index) in selectionPartyIds">
                <el-tag
                  :key="item.pid"
                  :closable="dialogType !== 'view'"
                  size="small"
                  @close="closeTag(selectionPartyIds, index, 'partyIds')"
                >
                  {{ item.name ? item.name : item.firstName }}
                </el-tag>
              </template>
            </div>
            <el-button
              class="suffix"
              type="primary"
              size="small"
              @click="selectInputVal(1)"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="权限菜单" prop="menuIds">
            <el-input
              placeholder="请选择……"
              readonly
              type="textarea"
              :rows="10"
              resize="none"
              v-model="formData.menuIds"
            >
            </el-input>

            <div
              class="content"
              :class="dialogType === 'view' ? 'view' : ''"
              v-if="formData.menuIds && formData.menuIds.length !== 0"
            >
              <template v-for="({ oid, name }, index) in selectionMenuIds">
                <el-tag
                  :key="oid"
                  :closable="dialogType !== 'view'"
                  size="small"
                  @close="closeTag(selectionMenuIds, index, 'menuIds')"
                >
                  {{ name }}
                </el-tag>
              </template>
            </div>
            <el-button
              class="suffix"
              type="primary"
              size="small"
              @click="selectInputVal(2)"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="md-component-btns">
      <el-button
        v-if="dialogType === 'view'"
        size="medium"
        type="primary"
        @click="dialogType = 'edit'"
        >编辑
      </el-button>
      <el-button
        v-if="dialogType !== 'view'"
        size="medium"
        type="primary"
        @click="save"
        >保存</el-button
      >
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>

    <el-dialog
      :visible.sync="visible"
      :title="selectionType === 1 ? '选择用户集合' : '选择权限菜单'"
      width="1000px"
      :modal-append-to-body="false"
    >
      <div style="width: 100%; height: 500px" v-if="visible">
        <avue-crud
          v-if="selectionType === 2"
          :option="menu.option"
          :data="menu.data"
          @selection-change="(v) => (menu.selection = v)"
          ref="crud1"
        >
        </avue-crud>

        <template>
          <div class="tableGroup header_" v-if="selectionType === 1">
            <div>组织</div>
            <div>用户组</div>
            <div>角色</div>
            <div>用户</div>
          </div>
          <div class="tableGroup" v-if="selectionType === 1">
            <!--组织-->
            <avue-crud
              :option="setOption(users.option, 'orgs')"
              :data="users.data.orgs"
              @selection-change="(v) => (users.selection.orgs = v)"
              ref="orgs"
            >
            </avue-crud>
            <!--用户组-->
            <avue-crud
              :option="setOption(users.option, 'usergroups')"
              :data="users.data.usergroups"
              @selection-change="(v) => (users.selection.usergroups = v)"
              ref="usergroups"
            >
            </avue-crud>
            <!--角色-->
            <avue-crud
              :option="setOption(users.option, 'roles')"
              :data="users.data.roles"
              @selection-change="(v) => (users.selection.roles = v)"
              ref="roles"
            >
            </avue-crud>
            <!--用户-->
            <avue-crud
              :option="setOption(users.option, 'users')"
              :data="users.data.users"
              @selection-change="(v) => (users.selection.users = v)"
              ref="users"
            >
            </avue-crud>
          </div>
        </template>
      </div>
      <div slot="footer">
        <el-button size="small" type="primary" @click="sure">确定</el-button>
        <el-button size="small" @click="visible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/api/menu";

export default {
  name: "jurisdictionTemp",
  data() {
    return {
      formData: {
        partyIds: "",
        menuIds: "",
      },
      rules: {
        partyIds: [
          { required: true, message: "请选择用户集合", trigger: "change" },
        ],
        menuIds: [
          { required: true, message: "请选择菜单集合", trigger: "change" },
        ],
      },
      selectionType: 1,

      visible: false,

      menu: {
        data: [],
        selection: [],
        option: {
          height: "450",
          calcHeight: 10,
          dialogWidth: 900,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          labelWidth: 120,
          menuWidth: 200,
          viewBtn: false,
          dialogClickModal: false,
          tabs: true,
          delBtn: false,
          addBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          align: "center",
          menu: false,
          rowKey: "oid",
          rowParentKey: "parentId",
          // tree: true,
          // lazy: true,
             defaultExpandAll: true,
          header: false,
          selection: true,
          column: [
            {
              align: "left",
              label: "菜单名称",
              prop: "name",
              slot: true,
            },
            {
              label: "菜单类型",
              prop: "alias",
            },
            {
              label: "路由",
              prop: "path",
            },
            {
              label: "排序",
              prop: "orders",
            },
            {
              label: "权限标识",
              prop: "code",
            },
            {
              label: "状态",
              prop: "enableFlag",
              dicData: [
                {
                  label: "启用",
                  value: 1,
                },
                {
                  label: "停用",
                  value: 0,
                },
              ],
            },
          ],
        },
        treeLoad(tree, treeNode, resolve) {
          const parentId = tree.oid + "";
          api.getMenuList({ parentId }).then((res) => {
            resolve(res.data.data);
          });
        },
      },

      users: {
        keys: [
          { key: "usergroups", label: "用户组" },
          { key: "roles", label: "角色" },
          { key: "orgs", label: "组织" },
          { key: "users", label: "用户" },
        ],
        // usergroups   roles   orgs    users
        data: {},
        selection: { usergroups: [], roles: [], orgs: [], users: [] },
        option: {
          height: "450",
          calcHeight: 10,
          dialogWidth: 900,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          labelWidth: 120,
          menuWidth: 200,
          viewBtn: false,
          dialogClickModal: false,
          tabs: true,
          delBtn: false,
          addBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          align: "center",
          menu: false,
          rowKey: "oid",
          rowParentKey: "parentId",
          tree: true,
          lazy: true,
          header: false,
          selection: true,
          column: [],
          usergroups: [{ label: "用户组名称", prop: "name" }],
          roles: [{ label: "角色名称", prop: "name" }],
          users: [{ label: "用户名称", prop: "username" }],
          orgs: [{ label: "组织名称", prop: "name" }],
        },
      },

      selectionPartyIds: [],
      selectionMenuIds: [],

      recirculationSelection: [],

      dialogType: "open",
    };
  },
  methods: {
    selectInputVal(val) {
      this.visible = true;
      this.selectionType = val;
      this.recirculationSelection =
        val === 1 ? this.selectionPartyIds : this.selectionMenuIds;

      this.$nextTick(() => {
        this.toggleRowSelection();
      });
    },
    setOption(option, objName) {
      let opt = this.deepCopy(option);
      opt.column = option[objName];
      return opt;
    },
    closeTag(data, index, model) {
      data.splice(index, 1);
      this.formData[model] = this.deepCopy(data)
        .map((item) => item[this.selectionType === 1 ? "pid" : "oid"])
        .join(",");
    },
    sure() {
      this.visible = false;
      if (this.selectionType === 1) {
        this.selectionPartyIds = [];
        let users = this.deepCopy(this.users.selection);
        for (const key in users) {
          const newArr = users[key];
          newArr.forEach((v) => {
            if (this.selectionPartyIds.every((k) => k.pid !== v.pid)) {
              this.selectionPartyIds.push(v);
            }
          });
        }
        this.formData.partyIds = this.deepCopy(this.selectionPartyIds)
          .map((item) => item.pid)
          .join(",");
        this.users.selection = {
          usergroups: [],
          roles: [],
          orgs: [],
          users: [],
        };
      } else {
        this.selectionMenuIds = this.deepCopy(this.menu.selection);
        this.formData.menuIds = this.deepCopy(this.menu.selection)
          .map((item) => item.oid)
          .join(",");
        this.menu.selection = [];
      }
    },
    save() {
      this.$refs["form"].validate((f) => {
        if (f) {
          this.formData.partyIds = this.deepCopy(this.selectionPartyIds)
            .map((item) => item.pid)
            .join(",");
          this.formData.menuIds = this.deepCopy(this.selectionMenuIds)
            .map((item) => item.oid)
            .join(",");
          if (this.dialogType === "open") {
            api.save(this.formData).then(() => {
              this.$emit("removeThisTabs");
              this.$message.success("保存成功");
              this.$emit("refresh");
            });
          } else {
            api.updateMenuAuth(this.formData).then(() => {
              this.$emit("removeThisTabs");
              this.$message.success("编辑成功");
              this.$emit("refresh");
            });
          }
        }
      });
    },
    open() {
      this.getMenu();
      this.getUsers();
      this.dialogType = "open";
    },
    edit(row) {
      this.getMenu();
      this.getUsers();
      this.getDetails(row);
      this.dialogType = "edit";
    },
    view(row) {
      this.getDetails(row);
      this.dialogType = "view";
    },

    getDetails(row) {
      api.getJurisdictionDetails({ id: row.oid }).then((res) => {
        let data = res.data.data;
        Object.assign(this.formData, data);
        this.selectionMenuIds = data.menuList;
        this.selectionPartyIds = data.partyList.filter((i) => {
          i.pid = i.oid;
          return i.pid;
        });
      });
    },
    getMenu() {
      let clientId = localStorage.getItem("appId");
      this.menu.data = [];
      api.getMenuTree({ }).then((res) => {
        this.menu.data = res.data.data;
      });
    },
    getUsers() {
      /*
       * usergroups  用户组
       * roles       角色
       * orgs        组织
       * users       用户列表
       * */
      api.getUserCollect().then((res) => {
        this.users.data = res.data.data;
      });
    },
    toggleRowSelection() {
      if (
        this.recirculationSelection &&
        this.recirculationSelection.length > 0
      ) {
        let ids = this.recirculationSelection.map((item) =>
          item.oid ? item.oid : item.pid
        );
        // 说明此列表不存在 oid
        // 整行数据转为 String 进行对比匹配
        if (this.selectionType === 2) {
          let data = this.recursion(this.menu.data);
          data.forEach((item) => {
            if (ids.includes(item.oid)) {
              this.$refs.crud1.toggleRowSelection(item, true);
              if (this.menu.selection.every((v) => v.oid !== item.oid)) {
                this.menu.selection.push(item);
              }
            }
          });
        } else {
          for (const key in this.users.data) {
            this.users.data[key].forEach((item) => {
              if (ids.includes(item.pid)) {
                this.$refs[key].toggleRowSelection(item, true);
                this.users.selection[key].push(item);
              }
            });
          }
        }
      }
    },
    recursion(data) {
      const result = [];
      data.forEach((item) => {
        const loop = (data) => {
          result.push(data);
          let child = data["children"];
          if (child) {
            for (let i = 0; i < child.length; i++) {
              loop(child[i]);
            }
          }
        };
        loop(item);
      });
      return result;
    },
  },
  watch: {
    "menu.data": {
      handler() {
        this.$nextTick(() => {
          this.toggleRowSelection();
        });
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  .el-row {
    .el-col {
      .el-form-item {
        .el-form-item__content {
          position: relative;

          .content {
            position: absolute;
            z-index: 99;
            top: 5px;
            left: 15px;
            width: calc(100% - 30px);
            height: calc(100% - 10px);
            background: white;
            overflow-y: scroll;

            .el-tag {
              margin-right: 5px;
            }

            > div {
              line-height: 1;
              font-size: 12px;
              font-weight: normal;
            }
          }

          .view {
            background: #f5f7fa;
          }

          .suffix {
            position: absolute;
            right: 10px;
            bottom: 10px;
            z-index: 100;
          }
        }
      }
    }
  }
}

.tableGroup {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: nowrap;

  .avue-crud {
    width: 24%;
  }
}

.header_ {
  > div {
    width: 25%;
    text-indent: 10px;
    padding-bottom: 5px;
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
